import MSConfig; MSConfig.init('.')
import MSLogger2; log = MSLogger2.get('wsgi_server')
import WorkerMSDB
import MSDBTemplates
import WorkerCOMSecurithor
import threading
import time

def Database_threadSync(isTerminated, objs, reader, threadSyncTimeout):
    if threadSyncTimeout == 0: threadSyncTimeout = 30

    ctr = 0
    objects = []
    MSDBTemplates.GET_MSObjects_FROM_CarOnline(reader.connection.cursor(), objects)
    log.info('Database::threadSync: started with timeout(%d) and reader(%s)', threadSyncTimeout, reader.getConnectionName())
    while not isTerminated.isSet():
        try:
            if ctr == 6:
                MSDBTemplates.GET_MSObjects_FROM_CarOnline(reader.connection.cursor(), objects)
                ctr = 0
            writer = WorkerCOMSecurithor.Worker(MSConfig.config.get('mswriter', 'port'))
            reader.readEventsPGSM(objects)
            reader.readEventsContactId(objects)
            reader.readEventsBolid(objects)
            writer.writeEventsStatic(objects)
            reader.finalyze(objects)
            #writer.connection.close()
            ctr += 1
            time.sleep(threadSyncTimeout)
        except Exception, err:
            log.error('Database::threadSync: %s', str(err))
        time.sleep(threadSyncTimeout)
    log.info('Database::threadSync: stopped')

class Database:
    def __init__(self, path):
        self.isTerminated = threading.Event(); self.isTerminated.clear()
        self.threadSyncMSDB     = None

    def setAutoSync(self, source, timeout):
        if timeout < 5: raise RuntimeError('wrong timeout value given')
        if source == 'msdb':
            MSConfig.init('.')
            reader = WorkerMSDB.Worker(MSConfig.config.get('msdb','host'),
                                       MSConfig.config.get('msdb','port'),
                                       MSConfig.config.get('msdb','dbname'),
                                       MSConfig.config.get('msdb','user'),
                                       MSConfig.config.get('msdb','pwd'))
            reader.connect()

            self.threadSyncMSDB = threading.Thread(None, Database_threadSync, 'DatabaseSyncMSDB', (self.isTerminated, None, reader, timeout))
            self.threadSyncMSDB.start()

    def start(self):
        log.info('Database::started')

    def stop(self):
        log.debug('Database::stop: ...')
        self.isTerminated.set()
        if self.threadSyncMSDB: self.threadSyncMSDB.join()
        log.info('Database::stop: done')

instance = None
def getInstance():
    global instance
    if instance == None: raise RuntimeError('Database instance is not created')
    return instance
